package com.qq.BFMRSE.trapDoor;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.Iterator;
import java.util.List;

import com.qq.BFMRSE.entity.BloomFilter;
import com.qq.BFMRSE.entity.encryptedIndex;
import com.qq.BFMRSE.entity.trapDoor;
import com.qq.BFMRSE.extractWord.wordTFAndIDFInfo;
import com.qq.BFMRSE.index.buildIndex;
import com.qq.BFMRSE.index.indexEncrypted;
import com.qq.BFMRSE.index.indexHelper;
import com.qq.BFMRSE.util.BFConstants;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;


public class GenTropDoor {
	private indexEncrypted inSk;
	public indexEncrypted getInSk(){
		return inSk;
	}
	public void setInSk(indexEncrypted inSk){
		this.inSk=inSk;
	}
	public GenTropDoor(indexEncrypted inSk){
		this.inSk=inSk;
	}
	public GenTropDoor(){}

	public trapDoor getTropDoor(List<String>wordList)
	{
		trapDoor resultTrapDoor=new trapDoor();
		double []trapdoorPlain=getSearchPlainIndex(wordList);
		encryptedIndex enIndex=EncryptedTroopHelper.encrypTropDoor(inSk,trapdoorPlain);
		resultTrapDoor.setMD1(enIndex.getMD1());
		resultTrapDoor.setMD2(enIndex.getMD2());
		BloomFilter bf=getBfFromWords(wordList);
		resultTrapDoor.setBf(bf);
		return resultTrapDoor;
	}
	public String getTrapJson(trapDoor trap)
	{
		//JsonConfig jsonConfig=new JsonConfig();
		//jsonConfig.setExcludes(new String[]{"bf"});
		JSONObject tempjO=JSONObject.fromObject(trap); 
		JSONObject jO=(JSONObject) JSONSerializer.toJSON(tempjO.toString());
		return jO.toString();
	}
	public String getTrapBitsInfo(BloomFilter bf)
	{
		BitSet bitSet=bf.getBits();
		List<Integer> list=new ArrayList<Integer>();
		for(int i=0;i<bitSet.length();i++)
		{
			if(bitSet.get(i))
			{
				list.add(i);
			}
		}
		JSONArray ja=JSONArray.fromObject(list);
		return ja.toString();
	}
	public double [] getSearchPlainIndex(List<String>wordList)
	{
		int n=indexHelper.wordList.size()+BFConstants.DUMMUYKWYWORDCOUNT;
		double []resultIndex=new double[n];
		for(int i=0;i<n;i++)
		{
			resultIndex[i]=0;
		}
		Iterator<String> iterator=wordList.iterator();
		while(iterator.hasNext())
		{
			String tempWord=iterator.next();
			int index=indexHelper.wordList.indexOf(tempWord);
			resultIndex[index]=wordTFAndIDFInfo.getIDFForWord(tempWord);
		}
		return resultIndex;
	}
	public BloomFilter getBfFromWords(List<String>wordlList)
	{
		BloomFilter resBf=new BloomFilter();
		Iterator<String>iterator=wordlList.iterator();
		while(iterator.hasNext())
		{
			String tempWord=iterator.next();
			resBf.addValue(tempWord);
		}
		return resBf;
	}

}
